package city.spring.modules.reception.controller;

import city.spring.modules.oldman.service.OldmanInfoService;
import city.spring.modules.reception.entity.OldmanServiceRecordEntity;
import city.spring.modules.reception.service.OldmanServiceRecordService;
import city.spring.modules.reception.service.OldmanVolunteerInfoService;
import city.spring.modules.reception.vo.OldmanServiceRecordVO;
import city.spring.modules.system.service.UserService;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.NonNull;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.ArrayList;
import java.util.List;

/**
 * Controller：志愿者服务记录
 *
 * @author pxm
 * @date 2020-07-01 11:16:48
 */
@RestController
@RequestMapping("/oldman_service_record")
public class OldmanServiceRecordController extends ApiController {
    private final OldmanServiceRecordService oldmanServiceRecordService;
    private final OldmanVolunteerInfoService oldmanVolunteerInfoService;
    private final OldmanInfoService oldmanInfoService;
    private final UserService userService;
    /**
     * 实体类可排序字段
     */
    private final List<SFunction<OldmanServiceRecordEntity, ?>> entityOrderFields;

    public OldmanServiceRecordController(OldmanServiceRecordService oldmanServiceRecordService, OldmanVolunteerInfoService oldmanVolunteerInfoService, OldmanInfoService oldmanInfoService, UserService userService) {
        this.oldmanServiceRecordService = oldmanServiceRecordService;
        this.oldmanVolunteerInfoService = oldmanVolunteerInfoService;
        this.oldmanInfoService = oldmanInfoService;
        this.userService = userService;
        entityOrderFields = new ArrayList<>();
        entityOrderFields.add(OldmanServiceRecordEntity::getId);
        entityOrderFields.add(OldmanServiceRecordEntity::getVolunteer);
        entityOrderFields.add(OldmanServiceRecordEntity::getContactNum);
        entityOrderFields.add(OldmanServiceRecordEntity::getOldman);
        entityOrderFields.add(OldmanServiceRecordEntity::getRecorder);
        entityOrderFields.add(OldmanServiceRecordEntity::getActivities);
        entityOrderFields.add(OldmanServiceRecordEntity::getServiceLength);
        entityOrderFields.add(OldmanServiceRecordEntity::getGmtCreate);
        entityOrderFields.add(OldmanServiceRecordEntity::getGmtModified);
    }

    /**
     * 获取全部的 <strong>志愿者服务记录</strong> 列表
     */
    @GetMapping("all")
    public Object listAll(@PageableDefault Pageable pageable, OldmanServiceRecordEntity entity) {
        LambdaQueryChainWrapper<OldmanServiceRecordEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        return success(lambdaQuery.list());
    }

    /**
     * 分页获取 <strong>志愿者服务记录</strong> 列表
     *
     * @param pageable 分页参数信息
     */
    @GetMapping
    public Object list(@PageableDefault Pageable pageable, OldmanServiceRecordVO entity) {
        QueryWrapper<? extends OldmanServiceRecordEntity> queryWrapper = buildQuery(entity);
        return success(oldmanServiceRecordService.listPage(MyBatisUtils.toPage(pageable), queryWrapper));
    }
//    public Object list(@PageableDefault Pageable pageable, OldmanServiceRecordEntity entity) {
//        LambdaQueryChainWrapper<OldmanServiceRecordEntity> lambdaQuery = buildLambdaQuery(entity);
//        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
//        Page<OldmanServiceRecordEntity> page = lambdaQuery.page(MyBatisUtils.toPage(pageable, false));
//        for (OldmanServiceRecordEntity record : page.getRecords()) {
//            try {
//                OldmanVolunteerInfoEntity oldmanVolunteerInfoEntity = oldmanVolunteerInfoService.getById(record.getVolunteer());
//                record.setVolunteerName(oldmanVolunteerInfoEntity.getName());
//                record.setContactNum(oldmanVolunteerInfoEntity.getPhone());
//
//            } catch (Exception ignore) {
//                record.setVolunteer(null);
//                record.setVolunteerName("< 找不到志愿者 >");
//            }
//            try {
//                OldmanInfoEntity oldmanInfoEntity = oldmanInfoService.getById(record.getOldman());
//                record.setOldmanName(oldmanInfoEntity.getOldmanName());
//            } catch (Exception ignore) {
//                record.setOldman(null);
//                record.setOldmanName("< 找不到老人 >");
//            }
//            try {
//                UserEntity userEntity = userService.getById(record.getRecorder());
//                record.setRecorderName(userEntity.getNickname());
//            } catch (Exception ignore) {
//                record.setRecorder(null);
//                record.setRecorderName("< 找不到记录人 >");
//            }
//        }
//        return success(page);
//    }

    /**
     * 获取一个 <strong>志愿者服务记录</strong>
     *
     * @param id 主键ID
     */
    @GetMapping("{id}")
    public Object info(@PathVariable String id) {
        Page<OldmanServiceRecordVO> page = new Page<>();
        QueryWrapper<OldmanServiceRecordVO> wrapper = new QueryWrapper<>();
        wrapper.eq("t1.id", id);
        IPage<OldmanServiceRecordVO> iPage = oldmanServiceRecordService.listPage(page, wrapper);
        List<OldmanServiceRecordVO> records = iPage.getRecords();
        if (records.isEmpty()) {
            return success(null);
        }
        return success(records.get(0));
    }

    /**
     * 添加一个 <strong>志愿者服务记录</strong>
     *
     * @param entity 修改后的信息
     */
    @PostMapping
    public Object add(@RequestBody OldmanServiceRecordEntity entity, @NonNull Principal user) {
        oldmanServiceRecordService.saveOldmanServiceRecord(entity, user);

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.LOCATION, String.valueOf(entity.getId()));
        return new ResponseEntity<>(headers, HttpStatus.CREATED);
    }

    /**
     * 修改一个 <strong>志愿者服务记录</strong>
     *
     * @param id     主键ID
     * @param entity 修改后的信息
     */
    @PutMapping("{id}")
    public Object update(@PathVariable String id, @RequestBody OldmanServiceRecordEntity entity) {
        entity.setId(id);
        oldmanServiceRecordService.updateOldmanServiceRecord(entity);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 删除一个 <strong>志愿者服务记录</strong>
     *
     * @param id 主键ID
     */
    @DeleteMapping("{id}")
    public Object delete(@PathVariable String id) {
        oldmanServiceRecordService.deleteOldmanServiceRecord(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong>志愿者服务记录</strong>
     *
     * @param ids 主键ID列表
     */
    @DeleteMapping
    public Object deleteIds(@RequestBody List<String> ids) {
        oldmanServiceRecordService.deleteOldmanServiceRecord(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<OldmanServiceRecordEntity> buildLambdaQuery(OldmanServiceRecordEntity entity) {
        LambdaQueryChainWrapper<OldmanServiceRecordEntity> lambdaQuery = oldmanServiceRecordService.lambdaQuery();
        lambdaQuery.eq(StringUtils.isNotBlank(entity.getId()), OldmanServiceRecordEntity::getId, entity.getId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getVolunteer()), OldmanServiceRecordEntity::getVolunteer, entity.getVolunteer());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getContactNum()), OldmanServiceRecordEntity::getContactNum, entity.getContactNum());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getOldman()), OldmanServiceRecordEntity::getOldman, entity.getOldman());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getRecorder()), OldmanServiceRecordEntity::getRecorder, entity.getRecorder());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getActivities()), OldmanServiceRecordEntity::getActivities, entity.getActivities());
        lambdaQuery.eq(entity.getServiceLength() != null, OldmanServiceRecordEntity::getServiceLength, entity.getServiceLength());
        lambdaQuery.eq(entity.getGmtCreate() != null, OldmanServiceRecordEntity::getGmtCreate, entity.getGmtCreate());
        lambdaQuery.eq(entity.getGmtModified() != null, OldmanServiceRecordEntity::getGmtModified, entity.getGmtModified());
        return lambdaQuery;
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private QueryWrapper<? extends OldmanServiceRecordEntity> buildQuery(OldmanServiceRecordVO entity) {
        QueryWrapper<? extends OldmanServiceRecordEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(entity.getId()), "t1.id", entity.getId());
        wrapper.like(StringUtils.isNotBlank(entity.getVolunteer()), "t1.volunteer", entity.getVolunteer());
        wrapper.like(StringUtils.isNotBlank(entity.getVolunteerName()), "t3.name", entity.getVolunteerName());
        wrapper.like(StringUtils.isNotBlank(entity.getContactNum()), "t1.contactNum", entity.getContactNum());
        wrapper.like(StringUtils.isNotBlank(entity.getOldman()), "t1.oldman", entity.getOldman());
        wrapper.like(StringUtils.isNotBlank(entity.getOldmanName()), "t2.oldman_name", entity.getOldmanName());
        wrapper.like(StringUtils.isNotBlank(entity.getVolunteerName()), "t3.name", entity.getVolunteerName());
        wrapper.like(StringUtils.isNotBlank(entity.getRecorderName()), "t4.username", entity.getRecorderName());
        wrapper.like(StringUtils.isNotBlank(entity.getRecorder()), "t1.recorder", entity.getRecorder());
        wrapper.like(StringUtils.isNotBlank(entity.getRecorder()), "t1.recorder", entity.getRecorder());
        wrapper.like(StringUtils.isNotBlank(entity.getRecorderName()), "t4.recorder_name", entity.getActivities());
        wrapper.eq(entity.getServiceLength() != null, "t1.service_length", entity.getServiceLength());
        wrapper.eq(entity.getGmtCreate() != null, "t1.gmt_create", entity.getGmtCreate());
        wrapper.eq(entity.getGmtModified() != null, "t1.gmt_modified", entity.getGmtModified());


        return wrapper;
    }

}
